import axios from "axios";
import { Message } from "element-ui"; // 项目用的element ui
// import router from '../router'

const service = axios.create({
  baseUrl: "https://127.0.0.1:8091/api",
  timeout: 7000 // 超过7秒提示超时
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // if (localStorage.getItem("access_token")) {
    //   config.headers["access_token"] = localStorage.getItem("access_token");
    // }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    if (res.status == 200) {
      // localStorage.setItem("access_token", res.data);
      return res;
    } else {
      Message({
        message: "报错了",
        type: "error",
        duration: 5 * 1000
      });
      return Promise.reject(new Error("发生错误了"));
    }
  },
  (error) => {
    if (error.response) {
      let code = error.response.status;
      if (code == 502) {
        Message({
          message: "登录过期,请重新登录!",
          type: "error",
          duration: 3 * 1000
        });
        return Promise.reject(new Error("登录过期,请重新登录"));
      }
      return Promise.reject("其他错误");
    } else {
      return Promise.reject("未知错误");
    }
  }
);
export default service;
